The Macromedia Code
Loyalty, justice, refined manners, purity—oh wait, the other kind of code. The source code. It runs strong in you, young padawan.
Now that you understand what Timeline effects are and how you create them, you can dig into the meat. Just so you know, the discussion will now notch up a level or two—the code is pretty advanced, what can we say? If you are a beginner at coding, just do as the rest of us and let your eyes glaze over at the hard parts. We assure you that the witty asides will not notch up at all. Not sure if that's a relief to you or not.
Just a quick note: We did not write these effects so while there sometimes may be comments about the programmer's intentions, you can read that as our best guess. (Happily, tutorials don't need to compile.) The code is pretty straightforward; however, sometimes things are done a certain way to avoid a certain consequence or to allow for a second potential use. There may be times that we miss these things. However, all code is written for a reason—usually a good one. Figuring out these reasons is the key to learning from the source of others.
Examining the Timeline Effect Code Structure
Macromedia code is structured much as you would expect, with the work centered around executeEffect and removeEffect. These methods actually just call the forward and reverse methods, which allows them to be called with parameters (nice for testing) and to be skipped easily (nice for testing as well). The most important reason to separate these methods, however, is so that you can call them again while the command is running. This is how the SWF preview works: You make an adjustment, the effect is run (the reverse and forward methods, that is), and a new SWF preview is generated and displayed. This would have been harder otherwise because the forward function takes parameters, while the built-in createEffect does not.
The code itself contains many alerts and traces. However, instead of calling these things directly, they call methods named things like doAlert and myTrace, which you can also turn on and off wholesale (nice for testing). All functions are wrapped in a try/catch block, which (sometimes) gives a trace of the problem when it fails (nice for testing as well). Do you see a pattern here? JavaScript can be a pain for testing already. Add to that a new API, no error messages, no code stepping, and the tendency to end a function at the first sign of a problem—you can see how putting a little tracing and flow-control stuff in here goes a long way.
Names in the new API can be quite verbose, to say the least. Not that they should have been named otherwise; it's just that between the long names and so many levels in things like symbols on a Timeline (document > timeline > layers[layer] > frames[frame] > elements ...), things can become pretty wordy. A few standard shorthand conventions here can help considerably. For example, "dom" and "tl" are always set as shorthand for fl.getDocumentDOM() and dom.getTimeline(), respectively. This makes everything more compact and readable once you know what is what. Other standards regarding names, capitalization, etc. are even more useful because you are passing names and calls around XML, JSFL, SWFs, and more. Discipline is essential to keep all this from flying apart—just as important as purity and refined manners.
The other really nice thing Macromedia did was create a very solid helper library (called shared.jsfl, as you might have guessed). This includes several utility methods for all those tedious things that you have to do right, such as convert slashes, create unique names, get something's start frame, and so on. There are also a few more specific functions, for generating and retrieving SWF previews. As always, there are many advantages to using libraries. Code can be reused and a bug fix needs to happen only in one spot. But mostly the little back-breaker things are much more likely to be addressed and corrected if they are just a function call away. Libraries can be loaded in JSFL just by running them (with fl.runScript), so they are super-convenient too.
The Drop Shadow Effect
The Drop Shadow effect is a pretty simple one as far as core functionality is concerned, yet it covers pretty much everything you would use in an effect. This time we start you with the code and work backwards to the editor and XML.
You can split the JSFL code into parts, the execute part and the remove part. However it also calls into some of the shared.jsfl functions, so those are loaded right at the start of each of these sequences. As we mentioned earlier, the executeEffect and removeEffect functions simply call the forward and reverse functions. The forward function takes arguments (preview, color, alpha, xOffset, yOffset), while the reverse function does not.

Here is a key point: When making effects, always keep in mind that whatever you do must be reversible or—perhaps better—resetable. Usually doing this is pretty complicated because you have to record the state of something before you alter it and then return it later to that state. Effects can be simpler that this, though, because you can design them to take place almost entirely inside the newly created symbol. They also never take more than one step forward without being reversed, so you only need to return to the start state. For example, while users may think they are moving a drop shadow when in Edit mode, they are actually taking off the shadow and then adding a new one. If they re-edit, it is taken off and recreated again. So when you go to remove the current effect, you don't need to set it back to the previous drop-shadow state (subtracting the current offsets, and so on). You can just delete the shadow and go back to one item on one frame. Then when the effect is re-executed, the shadow is recreated and put somewhere else. This is much simpler, and way more robust, than trying to back out of everything in the right order—especially considering that the previous values have all changed to the new settings at this point.

For the Drop Shadow effect this means creating the shadow on a separate layer. To reverse things, delete the layer. Simple, eh?
Effects that only take "one step" might suggest that undo does not work right, but that is not the case. Each time you create or edit an effect, Flash's undo/redo stack views that as a single transaction. You can see that by watching the History panel as you edit effects. Each remove/execute cycle is treated as a single step; inside that transaction there is no need for a separate undo/redo stack because things are always reversed before being recreated.
As to the shadow itself, it isn't a true shadow; it is just your selection made into a symbol, with its color and alpha adjusted. If you put a shadow on a few symbols, you can see how the overlaps are darker. It wouldn't be hard to break things apart first; reversing it would involve just deleting the shadow layer.
Here are the steps to create a drop shadow:
- Enter the symbol (edit in place).
- Convert the selection to a graphic.
- Add a new layer and put a copy of the graphic here.
- Move the copy and set the color and alpha.
- Exit the symbol.
- Update the preview SWF.
Creating the Drop Shadow
Because there aren't many lines of code, we can go over them all here. The whole thing is wrapped in a try/catch block, which simply traces an error if it fails. This does not trace every error in the book but, for example, using fl.getDocumentDominitrix will throw a type error because this function doesn't exist. Every bit helps. A try/catch in JavaScript looks like this:
try {//.... } catch (e) { fl.trace("Exception: " + e); }
Next you load the helper library and set your shorthand variables. Code is loaded in JavaScript much like in ActionScript—by running it. Seeing as the shared library is in Effects folder, you need to start with the fl.configURI variable (this is the Config folder location, which can be different on other machines):
fl.runScript(fl.configURI + "Effects/shared.JSFL");
Place all of these utilities in an Object-level variable (as functions) called Object.fxutil, which allows them to be accessed from anywhere.
fl.enableImmediateUpdates has also been turned on here, which allows the user to see Timeline changes as they happen. This is useful for debugging; for longer scripts, you might want to comment this out for speed and aesthetic reasons. It makes little difference with the Drop Shadow effect because it's all over so quickly.
Next you set the shorthand variables. It takes typing to save typing, and this was never truer than with JSFL. If you always use dom as your variable for the top level, that will be one less thing to worry about:
var dom = fl.getDocumentDOM();
Now to the actual coding part. First enter the symbol. This is done with the following:
dom.enterEditMode("inPlace");
There are two ways you can enter a symbol on the Timeline, just as in Flash: inPlace or newWindow. There is no point in opening a new window to edit because that would just aggravate the user. You don't have to expend any effort to find your effect symbol here. The only way you can edit an effect is if it's selected, so in this code you can assume that there is a current selection and that it is set to your effect. That already simplifies everything.
Now that you are inside the effect symbol, you need to convert everything that was selected to a graphic. This must happen because there could have been more than one symbol selected, or raw graphics involved. When adjusting the color/alpha, you need a symbol—ideally a single one. While creating a symbol from a selection is straightforward, you must keep in mind how this affects the library: there cannot be overlapping names; it is impolite to mess up someone else's neat library by throwing symbols into the root folder; and you must be able to find things that you make (to reverse them). So you need a way to generate a unique name, create your own library folder, and move the symbol there.
The shared.jsfl utilities come to the rescue—two in particular: generateLibName and moveToEffectsFolder. The generateLibName function sets a default folder name (Effects Folder) and symbol name (effectSymbol). If this combination exists, it adds "_n" (n being an incrementing number) to the symbol name until it finds an available one. The first valid name is returned. The moveToEffectsFolder function creates Effects Folder if it doesn't already exist and, of course, moves the symbol (passed as an argument) there. This greatly simplifies the Drop Shadow code:
var libName = Object.fxutil.generateLibName(); var mySymbolName = dom.convertToSymbol("graphic", libName, "top left"); Object.fxutil.moveToEffectsFolder(mySymbolName.name);
This should be self-explanatory by now: Get a valid name, create a symbol with it, and move it to Effects Folder.
So what was the current selection is now grouped into a symbol. You will need to make a copy of this for the drop shadow, but first you need to make the shadow layer. Note: In order to create and select a new layer, nothing can be selected on a different layer. You must deselect everything, make the new layer, and then put a copy of the symbol on the new layer. To facilitate this, a shortcut occurs here: The symbol is copied to the Clipboard in order to be pasted later on the new layer (using dom.clipCopy and dom.clipPaste). Although this is clean and easy, this procedure also destroys whatever was previously in the Clipboard. If you wish to avoid this problem in your own effects, place a library item on the Stage using library.addItemToDocument() with the path folder/name.
Manipulating the layer is somewhat complex but easy enough to follow step by step. Deselect things, make a "tl" shortcut to the current Timeline, and get the current layer's name:
dom.clipCopy();
dom.selectNone();
var tl = dom.getTimeline();
var mainLayerName = tl.getLayerProperty("name")
Add the new layer and name it xx Copy. It will be a normal layer (not a folder, mask, guide, and so on) and it will be added below the current layer (the last argument set to "true" adds it above the current layer). Because this returns the index of the new layer, you will want to keep this. Whew.
var layerIx = tl.addNewLayer(mainLayerName + " Copy", "normal", false);
Next the new layer is set to effectLayer. We're not sure about this—it seems to be just a marker that helps the remove function identify which layers are OK to remove. It isn't used in Drop Shadow but it appears in some effects that create more complex layered timelines. We don't think it is anything internal to the effects engine. Notice how you can add variables to objects like this, very useful:
var newLayer = tl.layers[layerIx];
newLayer.effectLayer = true;
Make sure the layer is selected and the currentLayer index points to your new one. This way the paste command sends your symbol to the correct layer:
tl.setSelectedLayers(layerIx, true);
tl.currentLayer = layerIx;
dom.clipPaste(true);
Now all that's left to do is move the shadow, color it, and set the alpha. You do this according to the passed parameters, which in turn were just taken from the activeEffect settings. It might be a good time to look at the executeEffect function and see how it calls your forward function:
function executeEffect()
{
var ef = fl.activeEffect;
forward( false, ef.color, ef.alpha, ef.xOffset, ef.yOffset );
}
function forward(preview, color, alpha, xOffset, yOffset)
{
// code
}
As you can see here, the properties are taken from the XML properties adjusted by the editor (much as you did in your own effect). This gives you access to the four properties you need to set the drop shadow. This part is pretty simple.
Move the pasted symbol and give it a simple name—shadow:
dom.moveSelectionBy({x:xOffset, y:yOffset});
var shadow = dom.selection[0];
Change the color. This is exactly how you would do it manually in Flash. The shift (>>) stuff just separates the long color hexadecimal number (RRGGBB) into its parts (RR, GG, BB):
shadow.colorMode = "advanced";
shadow.colorRedPercent = 0;
shadow.colorGreenPercent = 0;
shadow.colorBluePercent = 0;
shadow.colorRedAmount = ((color & 0xff0000) >> 16);
shadow.colorGreenAmount = ((color & 0x00ff00) >> 8);
shadow.colorBlueAmount = (color & 0x0000ff);
Set the alpha the same way:
shadow.colorAlphaAmount = 0;
shadow.colorAlphaPercent = alpha;
You're done! The only thing left now is to exit Edit mode and check whether you need to update the preview SWF. It uses the exportPreviewSWF utility function from the shared.jsfl library. However, because this effect preview isn't interactive (you must update it manually in the editor) there is no point in updating the SWF always right away:
dom.exitEditMode();
if (preview)
{
Object.fxutil.exportPreviewSWF( dom.selection[0] );
}
Removing the Drop Shadow Effect
Coding the removal of the effect is very similar in structure to adding it—actually, it is much simpler. Because there are no parameters, all the code takes place in the reverse method (which is called by removeEffect). Three main things happen here:
- Delete the second layer with the shadow.
- Break apart the originally created symbol.
- Clean up the library.
It begins the same way, loading the shared library, setting shorthand variables, and entering the currently selected symbol. The first thing it deletes is the second layer with the shadow (layers are zero-based, so this is layer 1):
dom.enterEditMode("inPlace");
var tl = dom.getTimeline();
tl.deleteLayer(1);
Next it breaks apart the remaining symbol and deletes it from the library. To do this you must first select it. You know it's the only thing on frame 1/layer 1, so you can do this with Select All:
tl.currentLayer = 0;
tl.currentFrame = 1;
dom.selectAll();
To delete the symbol from the library, you need to know which one it is. That's easy to find out at this point because any selected symbol has a libraryItem property. Once you break it apart, of course, finding the library entry will be much harder, so store it now for easy access. Afterwards, breaking it apart is just a method call:
var libItem = dom.selection[0].libraryItem;
dom.breakApart();
Now deleting from the library is easy because libraryItems have a name property you can use. Exit the symbol and you are pretty much done:
var libName = libItem.name;
dom.library.deleteItem(libName);
dom.exitEditMode();
There's one last thing to check. If this is the last effect, you'll leave Effects Folder empty. In keeping with the Macromedia Code, where refined manners are a way of life, you should check for this. Once again, the shared utilities are there for you:
if (Object.fxutil.folderIsEmpty())
{
fl.getDocumentDOM().library.deleteItem( Object.fxutil.getEffectsFolderName() );
}
That is it! Now create the XML file and hook up the editor.
Adding the Editor
The XML file is almost exactly like the XML file you used in your own effect, except that it uses a Flash interface instead of a pure XMLUI one. You can see the color, alpha, xOffest, and yOffset properties, as well as the defaultValue attribute that you didn't use in your effect:
<group name="Effects"> <effect name="Drop Shadow" /> <source file = "DropShadow.JSFL" /> <allow types = "button, shape, movie clip, graphic, text, bitmap" /> <properties> <!-- 17895690 = 0xffffff and 10066329 = 0x999999 --> <property name="Color" variable="color" min="0" max="17895690" defaultValue="10066329" type="Number" /> <property name="Alpha" variable="alpha" min="0" max="100" defaultValue="75" type="Number" /> <property name="X Offset" variable="xOffset" min="-1000" max="1000" defaultValue="10" type="Number" /> <property name="Y Offset" variable="yOffset" min="-1000" max="1000" defaultValue="10" type="Number" /> <property name="First" variable="first" defaultValue="1" type="Number" /> </properties> <!-- > buttons="accept, cancel"> --> <dialog id="dropshadow-dialog" title="Drop Shadow"> <flash id="dropshadow_ui" src="dropshadow.swf" width="772" height="456"> <property id="first" /> <property id="xOffset" /> <property id="yOffset" /> <property id="alpha" /> <property id="color" /> </flash> </dialog> </group>
In the <flash> tag you can see that there are also <property> tags. You can access these from the SWF (when run inside Flash) using the new XMLUI object. It has four methods:
XMLUI.get(propertyName)
XMLUI.set(propertyName, value)
XMLUI.accept()
XMLUI.cancel()
The get and set methods are for getting and setting these properties. The syntax is much as you would expect:
var al = XMLUI.get("alpha");
XMLUI.set("alpha", "50");
The accept and cancel methods are the equivalent of clicking OK or Cancel, so you can have them fire off when the user clicks these buttons in your SWF.
These four methods are enough to initiate basic interaction between your SWF and the effect code. ,However there is one other very useful thing to know. MMExecute is a way of running JSFL code from a SWF and it allows nearly limitless interactions. Of course, it only works when running in Flash (think security). Flash actually uses a slightly different player inside Flash, which is how the magic can happen here. MMExecute takes a text string of JSFL as an argument and returns whatever the given JSFL returns—though always in the form of a string (so a returned 42 would be "42"). As an example, to get the Config folder's URI from inside a SWF, you would use:
var uri = MMExecute("fl.configURI");
You can also call functions you've written. Here a SWF can call a function from the shared.jslf library:
MMExecute("Object.fxutil.getExportPreviewSWFFileName()");
As you can see, this allows the SWF to access anything JSFL has access to, which is pretty much everything. Looking at the editor, you can see extensive use of Macromedia's built-in components to create a nice interface; they simply communicate with the underlying effect.
While it is beyond the scope of this article (and no doubt unnecessary) to show how to make SWFs, it might be useful to look at how the preview SWFs are exported. This is a function in the shared library, called by the SWF when you click the Preview button.
Its logic goes like this:
- Find the object in the library.
- Convert it temporarily to a movie clip (so the preview plays).
- Export it to a known URI (ensure the Flash Player 7 format).
- Revert back to the previous type.
The function's full name is Object.fxutil.exportPreviewSWF and it takes an instance of a symbol as a parameter:
Object.fxutil.exportPreviewSWF = function(instance) {//...
Get the item in the library and convert it to a movie clip (saving the old type so you can revert it):
var libItem = instance.libraryItem;
var priorType = libItem.symbolType;
libItem.symbolType = "movie clip";
Get the known name (from another utility function that the SWF can call also):
var fileName = Object.fxutil.getExportPreviewSWFFullName();
Publish it. The only thing unusual here is that a new publish profile is created temporarily to ensure it is in Flash Player 7 format:
fl.getDocumentDOM().addNewPublishProfile( "__tmp_preview_profile" );
libItem.exportSWF( fileName );
fl.getDocumentDOM().deletePublishProfile( "__tmp_preview_profile" );
Restore the old symbol type and you are done:
libItem.symbolType = priorType;
Now the SWF or the JSFL can create a preview file using the current settings. Of course, if the settings have changed, the reverse and forward methods will have to be run to ensure that the effect is in the new state.
This should give you an idea of the total control you have over the editor and effect—the sky really is the limit. While the effects and the rest of the new Flash automation tools can help you get work done, they can also be a lot of fun to just fool around with.
In the next section we go over yet one more effect, the Transition effect. As you will see, it is pretty much all familiar territory by now.
Next: The Transition Effect
Documentation
- Live Docs
- JSAPI Docs
- Flash JavaScript Dictionary (PDF)
- JSAPI Update (flash_jsapi_help.mxp)
- JavaScript Developer Central (Netscape)
Mailing Lists
- ExtendFlash mailing list (FlashGuru)
External Links
- Introduction to the JSAPI (Guy Watson)
- Extending Flash MX 2004 (Keith Peters)
- XML to UI version 2.2 (Peter Brouwers)